package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.utils.RandomUtil;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    /**
     * 发送一个请求直接跳转到一个页面
     * springMVC viewcontroller:将请求和页面映射过来
     * @return
     */

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){

        //TODO 接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis()-1<60000){
                //60s内不能发送
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = RandomUtil.getFourBitRandom();


        //验证码的校验 key-phone,value-code

        //redis缓存验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone, code+"_"+System.currentTimeMillis(),5, TimeUnit.MINUTES);


        thirdPartFeignService.sendCode(phone,code);
        return R.ok("验证码发送成功");
    }

    /**
     *
     * TODO 重定向携带数据，利用session原理。将数据放在session中
     *      addFlashAttribute只要跳到下一个页面取出这个数据后，session里面的数据就会删除,只能取出一次
     *      addAttribute将数据放在url?后
     *
     *  TODO 分布式环境下session的问题
     * 重定向不能直接到页面，只能重定向到另一个控制器的路径
     * 重定向后保存在请求域中的值不会携带数据过去
     * <img src="/static/cart/ttributes模拟重定向并携带数据
     * @param vo
     * @param result
     * @param
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes attributes){
        if (result.hasErrors()){
            Map<String, String> map = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        HashMap<String, String> errors = new HashMap<>();
        //检验验证码
        String code = vo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.isEmpty(redisCode)){
            errors.put("code","验证码无效");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        if (!code.equals(redisCode.split("_")[0])){
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //删除验证码--->令牌机制
        redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        //开始注册，调用远程服务进行注册
        R r = memberFeignService.regist(vo);
        if (r.getCode()!=0){
            //失败
            errors.put("code",r.getData("msg",new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        return "redirect:http://auth.gulimall.com/login.html";
    }

    @GetMapping({"/login.html","/"})
    public String loginPage(HttpSession session){

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser==null){
            return "login";
        }

        return "redirect:http://gulimall.com";
    }

    /**
     * 登录
     * @param vo
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session){
        //远程登录
        R r = memberFeignService.login(vo);
        if (r.getCode()!=0){
            //失败
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code",r.getData("msg",new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

        MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
        });
        session.setAttribute("loginUser",data);
        return "redirect:http://gulimall.com";
    }
}
